//
//  KKLineChartView.m
//  KKBarViewDemo
//
//  Created by liaozhenming on 16/3/26.
//  Copyright © 2016年 liaozhenming. All rights reserved.
//

#import "KKLineChartView.h"

@interface KKLineChartContentView : UIView

@property (nonatomic, strong) NSArray* points;

@end


@implementation KKLineChartContentView

- (void)setPoints:(NSArray *)points {
    
    self.backgroundColor = [UIColor clearColor];
    _points = points;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    
    [self setClearsContextBeforeDrawing: true];
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGPoint linePoints[_points.count];
    
    for (NSInteger index = 0; index < _points.count; index++) {
        
        NSValue *pointValue = _points[index];
        CGPoint centerPoint = [pointValue CGPointValue];
        CGContextAddEllipseInRect(context, CGRectMake(centerPoint.x, centerPoint.y, 5, 5));
        [[UIColor blueColor] set];
        CGContextFillPath(context);
        
        linePoints[index] = CGPointMake(centerPoint.x + 2.5, centerPoint.y + 2.5);
    }
    
    CGContextAddLines(context, linePoints, _points.count);
    CGContextDrawPath(context, kCGPathStroke);
}

@end

#pragma mark - KKLineChartView methods

@interface KKLineChartView() {
    UIView *_verticalView;
    KKLineChartContentView *_chartContentView;
}

@end

@implementation KKLineChartView


- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        [self private_initContentView];
    }
    return self;
}

- (instancetype)init {
    return [self initWithFrame: CGRectZero];
}

- (void)awakeFromNib {
    [self private_initContentView];
}

#pragma mark - Private methods

- (void)private_initContentView {
    
    
    _verticalView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 20, CGRectGetHeight(self.bounds))];
    [self addSubview: _verticalView];
    
    _kk_contentScrollView = [[UIScrollView alloc] initWithFrame: CGRectMake(20, 0, CGRectGetWidth(self.bounds) - 20, CGRectGetHeight(self.bounds))];
    [self addSubview: _kk_contentScrollView];
}

- (void)private_getMaxValueOfValues:(NSArray*)values maxValue:(double *)maxValue{
    
    if (![values isKindOfClass: [NSArray class]]) {
        return;
    }
    
    for (id obj in values) {
        if ([obj isKindOfClass: [NSArray class]]) {
            [self private_getMaxValueOfValues: obj maxValue: maxValue];
        }
        else if ([obj isKindOfClass: [NSNumber class]]) {
            
            double itemValue = [obj doubleValue];
            if (*maxValue < itemValue) {
                *maxValue = itemValue;
            }
        }
        else if ([obj isKindOfClass: [NSString class]]) {
            double itemValue = [obj doubleValue];
            if (*maxValue < itemValue) {
                *maxValue = itemValue;
            }
        }
    }
}

- (void)private_updateItemValueWithMaxValue:(double)maxValue maxHeight:(CGFloat)maxHeight itemValues:(NSArray*)values{
    
    CGFloat offsetHeight = 10;
    CGFloat lateralItemOffsetWidth = 10;
    CGFloat lateralItemWidth = 20;
    
    NSMutableArray *centerPoints = [NSMutableArray array];
    
    for (NSInteger index = 0; index < values.count; index++) {
        CGFloat pointX = index *(lateralItemWidth + lateralItemOffsetWidth) + 10;
        //  绘制横轴上的值
        double itemValue = [values[index] doubleValue];
        
        NSString *title = [NSString stringWithFormat: @"%.1f",itemValue];
        if ([self.dataSource respondsToSelector: @selector(chartView:cellTitleAtIndex:)]) {
            title = [self.dataSource chartView: self cellTitleAtIndex: index];
        }
        
        float ratio = itemValue / maxValue;
        CGFloat itemViewHeight = ratio * maxHeight;
        
        CGPoint centerPoint = CGPointMake(pointX, maxHeight - itemViewHeight + offsetHeight);
        [centerPoints addObject: [NSValue valueWithCGPoint: centerPoint]];
    }
    
    _chartContentView = [[KKLineChartContentView alloc] initWithFrame: CGRectMake(0, 0, _kk_contentScrollView.contentSize.width, CGRectGetHeight(_kk_contentScrollView.bounds) - 10)];
    _chartContentView.points = centerPoints;
    [_kk_contentScrollView addSubview: _chartContentView];
}

#pragma mark - Public methods

- (void)reloadData {
    
    [_verticalView.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
    [_kk_contentScrollView.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
    
    if (self.dataSource == nil || ![self.dataSource respondsToSelector:@selector(valuesOfLateralAxisInLineChartView:)]) {
        return;
    }
    
    NSArray *values = [self.dataSource valuesOfLateralAxisInLineChartView: self];
    
    if (values == 0) {
        return;
    }
    
    double verticalMaxValue;
    [self private_getMaxValueOfValues: values maxValue: &verticalMaxValue];
    
    NSLog(@"verticalMaxValue = %f", verticalMaxValue);
    if (verticalMaxValue == 0) {
        return;
    }
    
    NSInteger lateralItemCount = [values count];
    
    //  绘制纵轴的坐标系
    double contentHeight = CGRectGetHeight(_kk_contentScrollView.bounds);
    CGFloat offsetHeight = 10;
    contentHeight -= offsetHeight * 2;    // 上下各10像素的空间
    {
        double verticalOffsetValue = verticalMaxValue / 10.0;
        
        double verticalOffsetHeight = contentHeight / 10.0;
        for (NSInteger index = 0; index < 11; index++) {
            
            UILabel *verticalTitleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, contentHeight - verticalOffsetHeight * index - 5 + offsetHeight, 20, 10)];
            verticalTitleLabel.backgroundColor = [UIColor clearColor];
            verticalTitleLabel.textAlignment = NSTextAlignmentRight;
            verticalTitleLabel.font = [UIFont systemFontOfSize: 8];
            verticalTitleLabel.textColor = [UIColor purpleColor];
            verticalTitleLabel.text = [NSString stringWithFormat: @"%.0f-",floor(verticalOffsetValue * index)];
            [_verticalView addSubview: verticalTitleLabel];
        }
        
        UIView *verticalLineView = [[UIView alloc] initWithFrame: CGRectMake(20, 0, 1, contentHeight + offsetHeight)];
        verticalLineView.backgroundColor = [UIColor purpleColor];
        [_verticalView addSubview: verticalLineView];
    }
    
    //  绘制横轴的坐标及其数据
    {
        
        CGFloat lateralItemOffsetWidth = 10;
        CGFloat lateralItemWidth = 20;
        
        id itemValue = [values firstObject];
        if ([itemValue isKindOfClass: [NSArray class]]) {
            lateralItemWidth = lateralItemWidth * [(NSArray*)itemValue count];
        }
        
        for (NSInteger index = 0; index < lateralItemCount; index++) {
            
            CGFloat pointX = index *(lateralItemWidth + lateralItemOffsetWidth);
            
            NSString *title = [NSString stringWithFormat: @"%@",@(index)];
            if ([self.dataSource respondsToSelector: @selector(chartView:lateralAxisTitleAtIndex:)]) {
                title = [self.dataSource chartView: self lateralAxisTitleAtIndex: index];
            }
            
            UILabel *lateralTitleLabel = [[UILabel alloc] initWithFrame: CGRectMake(pointX, contentHeight + offsetHeight, lateralItemWidth, 10)];
            lateralTitleLabel.backgroundColor = [UIColor clearColor];
            lateralTitleLabel.textAlignment = NSTextAlignmentCenter;
            lateralTitleLabel.font = [UIFont systemFontOfSize: 8];
            lateralTitleLabel.textColor = [UIColor purpleColor];
            lateralTitleLabel.text = title;
            [_kk_contentScrollView addSubview: lateralTitleLabel];
        }
        UIView *lateralLineView = [[UIView alloc] initWithFrame: CGRectMake(0, contentHeight + offsetHeight, lateralItemCount * (lateralItemWidth + lateralItemOffsetWidth), 1)];
        lateralLineView.backgroundColor = [UIColor purpleColor];
        [_kk_contentScrollView addSubview: lateralLineView];
        _kk_contentScrollView.contentSize = CGSizeMake(lateralItemCount * (lateralItemWidth + lateralItemOffsetWidth), 0);
    }
    
    //  绘制横轴上的值
    {
        [self private_updateItemValueWithMaxValue: verticalMaxValue maxHeight: contentHeight itemValues: values];
    }
}

@end
